package com.crazymaker.l2cache.monitor;

import com.crazymaker.l2cache.manager.CacheChannel;
import com.crazymaker.l2cache.redis.RedisGenericCache;
import com.crazymaker.springcloud.common.mpsc.ServiceThread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.LinkedBlockingQueue;

import static com.crazymaker.l2cache.monitor.MisRecordService.PERIOD;
import static com.crazymaker.springcloud.common.util.StringUtils.genRandomSrc;

public class HitRecordService extends ServiceThread {
    private static final Logger LOG = LoggerFactory.getLogger(HitRecordService.class);
    public static final String HIT_SUMMARY_KEY = "hit";
    private static LinkedBlockingQueue<Long> timeQueue = new LinkedBlockingQueue<>();
    private final CacheChannel cacheChannel;
    private final PrometheusCustomMonitor prometheusCustomMonitor;
    int setValPre;

    public HitRecordService(CacheChannel cacheChannel, PrometheusCustomMonitor prometheusCustomMonitor) {
        this.cacheChannel = cacheChannel;
        this.prometheusCustomMonitor = prometheusCustomMonitor;
        setValPre = genRandomSrc();
    }

    public void incrementHit() {
        timeQueue.add(MillisecondTimer.SINGLETON.now());
       // this.wakeup();
    }

    @Override
    public void run() {
        LOG.debug(this.getServiceName() + " service started");

        while (!this.isStopped()) {
            this.waitForRunning(1000);

            Long time = null;
            //业务代码
            RedisGenericCache redisGenericCache = (RedisGenericCache) cacheChannel.getHolder().getLevel2Cache("summary");
            while ((time = timeQueue.poll()) != null) {
                redisGenericCache.zadd(HIT_SUMMARY_KEY, time, String.format("%d#%d", setValPre, time));
            }

            if(null!=time) {
                redisGenericCache.zremrangeByScore(HIT_SUMMARY_KEY, 0, time - PERIOD);
                Long sum = redisGenericCache.zcard(HIT_SUMMARY_KEY);
                prometheusCustomMonitor.recordHit(sum);
            }
        }

        LOG.debug(this.getServiceName() + " service end");
    }

    @Override
    public String getServiceName() {
        return "L3Cache HitRecord Service";
    }
}

